package api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
	"seat-service/response"
	service "seat-service/service/impl"
	"seat-service/utils"
)

var studentService service.StudentService

type StudentApi struct {
}

func (*StudentApi) Login(c *gin.Context) {
	par := &model.Student{}
	err := c.ShouldBind(par)
	if err != nil || par.Name == "" || par.StudentNumber == 0 {
		initialization.SeatLogger.Error("c.ShouldBind(par) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	if err := studentService.LoginByNameAndStudentNumber(par); err != nil {
		initialization.SeatLogger.Error("studentService.LoginByNameAndStudentNumber(par) failed", zap.Error(err))
		resp.Fail(c, response.CodeUserNoExit, nil)
		return
	}
	userClass := utils.UserClaims{
		Username: par.Name,
		ID:       par.ID,
	}
	token, _ := jwt.GenToken(userClass)
	data := dto.LoginResponse{
		Name:  par.Name,
		Head:  par.Head,
		Token: token,
	}
	resp.Success(c, response.CodeSuccess, data)
}

func (*StudentApi) WxLogin(c *gin.Context) {
	code := c.Query("code")
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", initialization.Config.Wx.AppID, initialization.Config.Wx.AppSecret, code)
	respon, err := http.Get(url)
	if err != nil {
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	defer respon.Body.Close()
	var wxResponse dto.WxLoginResponse
	if err := json.NewDecoder(respon.Body).Decode(&wxResponse); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to parse QQ API response"})
		return
	}
	student := studentService.GetByOpenid(wxResponse.Openid)
	// 学生不存在注册
	if student.ID == 0 {
		student.Openid = wxResponse.Openid
		studentService.Create(&student)
	}
	userClass := utils.UserClaims{
		Username: student.Name,
		ID:       student.ID,
	}
	token, _ := jwt.GenToken(userClass)

	wxResponse.Token = token

	resp.Success(c, response.CodeSuccess, wxResponse)
}
